﻿namespace PowerSong.UserInterface
    {
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using PowerSong.BibleSupport;

    /// <summary>
    /// Represents a Bible translation manager that manages Bible translations across all databases.
    /// </summary>
    public static class BibleTranslationManager
        {

        /// <summary>
        /// Gets the list of available Bible translations.
        /// </summary>
        /// <returns>A list of available Bible translation names (without the .Bible extension).</returns>
        public static string[] GetTranslations()
            {

            var result = new List<string>();
            foreach (var fileName in Directory.GetFiles(State.AppDataLocation, "*.Bible"))
                {
                result.Add(Path.GetFileNameWithoutExtension(fileName));
                }
            return result.OrderBy(name => name).ToArray();

            }

        /// <summary>
        /// Determines whether the specified Bible translation is installed.
        /// </summary>
        /// <param name="translation">The Bible translation.</param>
        /// <returns>
        /// <c>true</c> if the specified Bible translation is installed; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsTranslationInstalled(string translation)
            {

            var translations = GetTranslations();
            foreach (var installedTranslation in translations)
                {
                if (installedTranslation.ToUpper() == translation.ToUpper()) return true;
                }
            return false;

            }

        /// <summary>
        /// Deletes the given Bible translation.
        /// </summary>
        /// <param name="translation">The Bible translation to delete.</param>
        public static void DeleteTranslation(string translation)
            {

            // Check the file exists
            var archiveFileName = Path.Combine(State.AppDataLocation, translation + ".Bible");
            var indexFileName = Path.Combine(State.AppDataLocation, translation + ".Index");
            if (!File.Exists(archiveFileName)) throw new ApplicationException("The given translation does not exist.");

            // Remove the bible and associated index
            File.Delete(archiveFileName);
            if (File.Exists(indexFileName)) File.Delete(indexFileName);

            }


        public static void InstallTranslation(string archiveFileName, string indexFileName = "")
            {

            // Install the bible translation
            var destinationArchiveFileName = Path.Combine(State.AppDataLocation, Path.GetFileNameWithoutExtension(archiveFileName) + ".Bible");
            var destinationIndexFileName = Path.Combine(State.AppDataLocation, Path.GetFileNameWithoutExtension(archiveFileName) + ".Index");
            if (File.Exists(destinationArchiveFileName))
                {
                throw new ApplicationException("The translation is already installed.");
                }
            File.Copy(archiveFileName, destinationArchiveFileName);

            // Create an index if necessary
            if (!string.IsNullOrEmpty(indexFileName))
                {

                // Install an existing index
                if (File.Exists(destinationIndexFileName)) File.Delete(destinationIndexFileName);
                File.Copy(indexFileName, destinationIndexFileName);

                }
            else
                {

                // Create a new index
                BibleIndex.CreateIndexFile(destinationArchiveFileName, destinationIndexFileName);

                }

            }

        public static void InstallTranslation(byte[] data, string translationName)
            {

            // Install the bible translation
            var destinationArchiveFileName = Path.Combine(State.AppDataLocation, translationName + ".Bible");
            var destinationIndexFileName = Path.Combine(State.AppDataLocation, translationName + ".Index");
            if (File.Exists(destinationArchiveFileName)) throw new ApplicationException("The translation is already installed.");

            try
                {

                // Save the translation
                File.WriteAllBytes(destinationArchiveFileName, data);

                // Create a new index
                BibleIndex.CreateIndexFile(destinationArchiveFileName, destinationIndexFileName);

                }
            catch (Exception ex)
                {
                
                if (File.Exists(destinationArchiveFileName)) File.Delete(destinationArchiveFileName);
                if (File.Exists(destinationIndexFileName)) File.Delete(destinationIndexFileName);
                throw new Exception("The translation could not be installed because it is corrupt or you do not have permission to save the translation to disk.", ex);

                }

            }

        public static BibleIndex LoadTranslation(string translationName)
            {
            var archiveFileName = Path.Combine(State.AppDataLocation, translationName + ".Bible");
            var indexFileName = Path.Combine(State.AppDataLocation, translationName + ".Index");
            return BibleIndex.Load(archiveFileName, indexFileName);
            }

        }

    }
